<?php
/**
 * Admin controller
 *
 * @uses       Zend_Controller_Action
 * @package    FireFeed
 * @subpackage Controller
 */
class AdminController extends Zend_Controller_Action
{
    /**
     * This will initialize CSS and javascript for the template system
     * 
     * @return void
     */
    public function init()
    {
    	$auth = Zend_Auth::getInstance();
        
    	if($auth->hasIdentity()) {
        	$this->view->username = $auth->getIdentity()->userProfile->nickname;
        }
        
        $this->_helper->layout->setLayout('adminlayout');
        
        $this->view->headScript()->appendFile('/js/jquery.form.js');
        $this->view->headScript()->appendFile('/js/formjs.js');
        $this->view->headScript()->appendFile('/js/admin.js');
        $this->view->headLink()->appendStylesheet('/css/tooltip.css');
    }
    
    /**
     * The "index" action is the default action for all controllers
     *
     * Assuming the default route and default router, this action is dispatched 
     * via the following urls:
     * - /
     * - /index/
     * - /index/index
     *
     * @return void
     */
    public function indexAction()
    {
    }
    
    public function loginAction()
    {
    	//clean headScript e headLink
    	$this->view->headScript()->exchangeArray(array());
    	$this->view->headLink()->exchangeArray(array());
    	
    	$this->view->headLink()->appendStylesheet('/css/style.css');
    	
    	$this->_helper->layout->setLayout('ffadminlayout');
    	$request = $this->getRequest();
    	
    	if ($request->isPost()) {
    		$form = new Form_Loginffadmin();
    		$post = $request->getPost();

    		if ($form->isValid($post)) {
    			$values = $form->getValues();
    			
    			$serviceFactory = Model_Factory::getInstance();
    			$service = $serviceFactory->getAuthService();
    			
  				$authResult = $service->authenticate(
  				    $values['username'], 
   				    $values['password']
   				);
	    		if (!$authResult) { // Autenticazione fallita
	    			$this->view->errorMsg = 
                        $this->_translate->translate('authError'); 
                    
                    $this->view->formLoginffadmin = $form;
                    return $this->render('ffadmin');
	            } else { // Autenticazione avvenuta con successo
	                $this->_redirect('/index/admin');
	            }
    		} else { // Validazione fallita
    			$this->view->formLoginffadmin = $form;
    			return $this->render('/auth/ffadmin', null, true);
    		}
    	} else { // Request type is not in POST so forward to index page
    		$this->_forward('ffadmin');
    	}
    }
    
    /**
     * Pagina dedicata alla gestione e all'inserimento dei feed da visualizzare 
     * all'utente GUEST nella index di FireFeed 
     * 
     * @return void
     */
    public function manageindexAction()
    {}
    
    
    /**
     * Pagina dedicata alla gestione da parte dell'amministratore degli utenti
     * registrati all'applicazione 
     * 
     * @return void
     */
    public function manageusersAction()
    {}
    
    /**
     * Pagina dedicata alla gestione da parte dell'amministratore dei feed 
     * presenti nel sistema 
     * 
     * @return void
     */
    public function managefeedsAction() 
    {}
    
    /**
     * Pagina dedicata alla gestione da parte dell'amministratore dei Feed Box 
     * nella index di FireFeed
     * 
     * @return void
     */
    public function manageindexpageboxAction()
    {
        $this->_helper->layout->disableLayout();
        
        $this->view->boxHistoryForm = new Form_BoxHistory();
    }
    
    /**
     * Reatrieve all boxes and render them in a list
     * - Ajax action
     * 
     * @return void
     */
    public function loadboxeslistAction()
    {
        $this->_helper->layout->disableLayout();
        
        $searchSession = new Zend_Session_Namespace('searchbox');
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            $form = new Form_BoxHistory();
            $post = $request->getPost();

            if ($form->isValid($post)) {
                $values = $form->getValues();
                
                $factory = Model_Factory::getInstance();
                $service = $factory->getBoxService();
                
                if (0 == $this->_getParam('page', 0)) {
                    $searchSession->unsetAll();
                    $searchSession->isPublished = $form->getValue('isPublished');
                    $searchSession->contains = $form->getValue('contains');
                }
                
                $criteria = array();
                $criteria['isPublished'] = $searchSession->isPublished;
                $criteria['contains'] = $searchSession->contains;
                
                $boxes = new Zend_Paginator($service->searchBoxes($criteria));
                $boxes->setCurrentPageNumber($this->_getParam('page', 1));
                $boxes->setItemCountPerPage(5);
                $boxes->setPageRange(5);
                
                $this->view->boxes = $boxes;
            } else {
                $translate = Zend_Registry::get("Zend_Translate");
                $localeMsg = $translate->translate("invalidparam");
                $this->getResponse()->appendBody($localeMsg);
            }
        }
    }
    
    /**
     * Load the form to add a new box
     * - Ajax action
     *  
     * @return void
     */
    public function activeaddindexpageboxAction()
    {
        $this->_helper->layout->disableLayout();
        
        $this->view->formAddIndexPageBox = new Form_IndexBox();
    }
    
    
    /**
     * Add a new feed box to the homepage
     * - Ajax action
     * 
     * @return void
     */
    public function addindexpageboxAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost();
            $form = new Form_IndexBox();
            
            if ($form->isValid($post)) {
                $resultArray = array('error' => false);
                $factory = Model_Factory::getInstance();
                $service = $factory->getBoxService();
                
                $feed = new Model_Entity_Feed();
                $feed->setOid($form->getValue('feed'));
                
                $box = new Model_Entity_Homepagebox($form->getValues());
                $box->setFeed($feed);
               
                $service->addBox($box);
            } else {
                $messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        } else {
            $this->_forward('activeaddindexpagebox');
        }    
    }
    
    /**
     * Load manage categories form
     * 
     * @return void
     */
    public function managecategoriesAction()
    {}
    
    /**
     * Published and not Published box
     * - Ajax action
     * 
     * @return void
     */
    
    public function setboxpublishedAction() 
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $translate = Zend_Registry::get("Zend_Translate");
        $localeMsg = $translate->translate("ajaxError");
        
        $resultArray = array('error'   => true,
                             'message' => $localeMsg);
        
        $isPublished = $this->_getParam('valueToSet', 2);
        $boxID = $this->_getParam('elementID', 0);
        
        if (($isPublished >= 0 && $isPublished < 2) && 0 < $boxID) {
            
            $factory = Model_Factory::getInstance();
            $service = $factory->getBoxService();
                        
            $box = new Model_Entity_Homepagebox();
            $box->setOid($boxID);
            $box->setIsPublished($isPublished);
            
            $service->setPublished($box);
            
            $resultArray = array('error' => false);
        }

        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    
    /**
     * Delete a box
     * - Ajax action
     * 
     * @return void
     */
    public function deleteboxAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $boxID = $this->_getParam('elementID');
        
        if (!empty($boxID) && is_numeric($boxID) && ($boxID > 0)) {
            $factory = Model_Factory::getInstance();
            $service = $factory->getBoxService();
            
            $feed = new Model_Entity_Feed();
            $feed->setOid($boxID);
            
            try {
                $service->deleteBox($boxID);
            } catch (Model_ZendDb_CantDeleteException $e) {
                $message = $this->_translate->translate('cantdelete');
                $resultArray = array('error' => true,
                                     'message' => $message);
            }
        } else {
            $message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
}    